package com.ych.modules.base.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ych.modules.base.dbEntity.TSysRoleEntity;
import com.ych.modules.base.mapper.TSysRoleMapper;
import com.ych.modules.base.service.IRSysRoleMenuService;
import com.ych.modules.base.service.IRUserInfoSysRoleService;
import com.ych.modules.base.service.ITSysRoleService;
import com.ych.modules.base.service.ITUserInfoService;
import com.ych.utils.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/5
 * Time: 15:41
 * Description:
 */
@Service("ITSysRoleService")
public class TSysRoleServiceImpl extends ServiceImpl<TSysRoleMapper, TSysRoleEntity> implements ITSysRoleService {
    @Autowired
    private IRSysRoleMenuService     irSysRoleMenuService;
    @Autowired
    private ITUserInfoService        itUserInfoService;
    @Autowired
    private IRUserInfoSysRoleService irUserInfoSysRoleService;

    @Override
    public void save(TSysRoleEntity role) {
        role.setCreateTime(new Date());
        role.setRoleId(UUID.randomUUID());
        role.setCreateTime(new Date());
        role.setStatus("0");
        this.insert(role);
        //检查权限是否越权
        this.checkPerems(role);
        //保存角色与菜单关系
        irSysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void update(TSysRoleEntity role) {
        this.updateById(role);
        //检查权限是否越权
        this.checkPerems(role);
        //更新角色与菜单关系
        irSysRoleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void delete(String[] roleIds) {
        //删除角色
        this.deleteBatchIds(Arrays.asList(roleIds));
        //删除角色与菜单关联
        irSysRoleMenuService.deleteBatch(roleIds);
        //删除角色与用户关联
        irUserInfoSysRoleService.deleteBatch(roleIds);
    }

    /**
     * 检查权限是否越权
     */
    private void checkPerems(TSysRoleEntity role) {
        //如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
        if ("1".equals(role.getCreateUserId())) {
            return;
        }
        //查询用户所拥有的菜单列表
        List<String> menuIdList = itUserInfoService.queryAllMenuId(role.getCreateUserId());
        //判断是否越权
        if (!menuIdList.containsAll(role.getMenuIdList())) {
            throw new RuntimeException("新增角色的权限，已超出你的权限范围");
        }
    }
}
